import { loginApi, getTopUpApi, topUpApi } from "@/sheep/api/baseApi";
import { baseUrl, tenantId, clientId, gzhAppid } from '@/sheep/request/baseUrl'
import store from '@/sheep/store'
import { bindAgentId } from "@/sheep/utils/common";

/**
 * 微信小程序授权登陆
 * @param {*} isBindPhone 是否需要绑定手机号
 * @returns
 */
export const xcxLogin = (isBindPhone) => {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: "weixin",
            success: function (loginRes) {
                const loginBody = {
                    xcxCode: loginRes.code,
                    isBindPhone: isBindPhone || false,
                    clientId: clientId,
                    grantType: "xcx",
                    tenantId: tenantId,
                };
                loginApi(loginBody).then((res) => {
                    if (res.code === 200) {
                        store.commit('user/setToken', res.data.access_token)
                        if (uni.getStorageSync('bindAgentId')) bindAgentId()
                        let path = uni.getStorageSync("pagePath");
                        setTimeout(() => {
                            uni.reLaunch({
                                url: '/' + path,
                            })
                        }, 1000)
                    }
                    if (res.code === 402) {
                        store.commit('user/setWxcode', res.msg)
                        store.commit('user/setAuth', true)
                    }
                });
            },
            fail(res) {
                console.log(res, "登录失败");
            },
        });
    });
}

/**
 * 微信小程序绑定手机号登陆
 * @param {*} code 手机号code
 * @returns
 */
export const xcxBindPhoneLogin = (code) => {
    return new Promise((resolve, reject) => {
        let loginBody = {
            xcxCode: uni.getStorageSync("wxcode"),
            phoneCode: code,
            clientId: clientId,
            grantType: "xcxBind",
            tenantId: tenantId,
        };
        loginApi(loginBody).then((res) => {
            if (res.code === 200) {
                store.commit('user/setToken', res.data.access_token)
                resolve(true);
                const pages = getCurrentPages();
                const currentPage = pages[pages.length - 1].route;
                uni.reLaunch({
                    url: "/" + currentPage,
                });
            } else {
                resolve(false);
            }
        });
    });
}

/**
 * 微信公众号授权跳转
 * @param {*} proxyPath 页面代理路径(默认h5)
 * @param {*} pagePath 授权后回到的页面路径(默认首页) - 注意在回到的路径里需要引入公众号登陆方法
 * @returns
 */
export const gzhAuthRedirect = (proxyPath, pagePath) => {
    return new Promise((resolve, reject) => {
        //打开链接
        let url = baseUrl.replace("api", proxyPath || "h5") + '/' + (pagePath || "")
        let hrefUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${gzhAppid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
        if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
            location.href = hrefUrl//此处判断是否为ios后,使用location.href跳转
        } else {
            window.location.href = hrefUrl//安卓跳转
        }
    });
}

/**
 * 微信公众号授权登陆
 * @param {*} isBindPhone 是否需要绑定手机号
 * @returns
 */
export const gzhLogin = (isBindPhone) => {
    return new Promise((resolve, reject) => {
        let url = window.location.href;
        let isToken = uni.getStorageSync("token");
        if (url.indexOf("code") > -1 && !isToken) {
            //获取code
            const code = url.split("code=")[1].split("&")[0];
            let loginBody = {
                xcxCode: code,
                isBindPhone: isBindPhone || false,
                clientId: clientId,
                grantType: "gzh",
                tenantId: tenantId,
            };
            loginApi(loginBody).then((res) => {
                if (res.code == 200) {
                    uni.setStorageSync("token", res.data.access_token);
                }
            });
        }
    });
}

/**
 * 微信小程序支付
 * @param {*} amount  支付金额
 * @param {*} orderId 订单id
 * @param {*} orderType 支付业务类型
 * @param {*} desc 商品描述
 * @returns true: 支付成功，false：支付失败
 */
export const xcxTopUp = (amount, orderId, orderType, desc) => {
    return new Promise((resolve, reject) => {
        const topUpForm = {
            payWay: "WX_XCX_PAY",
            amount: Number(amount).toFixed(2),
            orderType: orderType,
            attach: orderId,
            desc: desc,
        };
        topUpApi(topUpForm).then(({ data }) => {
            uni.requestPayment({
                provider: "wxpay",
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.packageValue,
                signType: data.signType,
                paySign: data.paySign,
                success: function (res) {
                    resolve(true);
                },
                fail: function (err) {
                    console.log("支付失败", err);
                    resolve(false);
                },
            });
        });
    });
}

/**
 * 微信公众号支付
 * @param {*} amount  支付金额
 * @param {*} orderId 订单id
 * @param {*} orderType 支付业务类型
 * @param {*} desc 商品描述
 * @returns true: 支付成功，false：支付失败
 */
export const gzhTopUp = (amount, orderId, orderType, desc) => {
    return new Promise((resolve, reject) => {
        const topUpForm = {
            payWay: "WX_XCX_PAY",
            orderType: orderType,
            amount: amount,
            attach: orderId,
            desc: desc,
        };
        topUpApi(topUpForm).then(({ data }) => {
            WeixinJSBridge.invoke(
                "getBrandWCPayRequest",
                {
                    appId: data.appId,
                    timeStamp: data.timeStamp,
                    nonceStr: data.nonceStr,
                    package: data.packageValue,
                    paySign: data.paySign,
                    signType: data.signType,
                },
                function (res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                        // 支付成功的处理逻辑
                        uni.showToast({
                            title: "微信支付成功",
                            icon: "none",
                        });
                        resolve(true);
                    } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                        // 支付失败的处理逻辑
                        uni.showToast({
                            title: "取消支付",
                            icon: "none",
                        });
                        resolve(false);
                    } else {
                        uni.showToast({
                            title: "支付失败",
                            icon: "none",
                        });
                        resolve(false);
                    }
                }
            );
        });
    });
}

/**
 * 拉起确认收货组件 (微信支付成功后，调用此方法)
 * @param {string} orderId 订单id
 * @returns true: 确认收货成功，false：确认收货失败
 */
export const wxReceiving = (orderId) => {
    return new Promise((resolve, reject) => {
        getTopUpApi(orderId).then((res) => {
            //拉起确认收货组件
            if (res.code == 200) {
                if (wx.openBusinessView) {
                    wx.openBusinessView({
                        businessType: "weappOrderConfirm",
                        extraData: {
                            merchant_id: res.data.mchId,
                            merchant_trade_no: res.data.topUpId,
                            transaction_id: res.data.transactionId,
                        },
                        success() {
                            resolve(true);
                        },
                        fail(errormsg) {
                            console.log("fail", errormsg);
                            resolve(false);
                        },
                        complete(errormsg) {
                            console.log("complete", errormsg);
                        },
                    });
                } else {
                    //引导用户升级微信版本
                    uni.showToast({
                        title: "微信版本过低，无法使用此功能，请升级到最新微信版本后重试。",
                        duration: 1500,
                    });
                }
            }
        });
    });
}

/**
 * 订阅微信模版信息
 * @param {*} tmplIds 模板id数组,最多三个 例: ["LygIpCmFE69qN9q-CL4FJuHybp1ZepgFhQqSON1G_pc"]
 * @returns true: 订阅成功，false：订阅失败
 */
export const subscribe = (tmplIds) => {
    return new Promise((resolve, reject) => {
        uni.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
                resolve(true);
            },
            fail(err) {
                console.log("err:", err);
                resolve(false);
            }
        });
    });
}